package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 判断手机号是否符合规范
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号不符合规范");
        }
        // 发送验证码
        String code = RandomUtil.randomNumbers(6);
        // 将验证码保存到redis中
        redisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code);
        // 记录日志
        log.info("发送验证码成功，验证码：{}",code);
        // 保存登录信息
        return Result.ok();
    }

    /**
     * 登录
     * @param loginForm
     * @param session
     * @return
     */
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 验证手机号
        String phone = loginForm.getPhone();
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }
        // 验证验证码
        String code = loginForm.getCode();
        String redisCode = redisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY+phone);
        if (code == null || !code.equals(redisCode))
        {
            return Result.fail("验证码错误！");
        }
        // 数据库是否存在该用户
        User user = query().eq("phone", phone).one();
        if(user == null) {
            user = createUser(phone);
            save(user);
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        // 将用户信息存入redis
        String token = UUID.randomUUID().toString();
        Map<String,Object> mp = new HashMap<>();
        mp.put("id",""+userDTO.getId());
        mp.put("nickName",userDTO.getNickName());
        mp.put("icon",userDTO.getIcon());
        redisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,mp);
        // 存储登录信息
        UserHolder.saveUser(userDTO);
        // 7.4.设置token有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,
                RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return Result.ok(token);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        // key
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = USER_SIGN_KEY + userId.toString() + keySuffix;
        Long offset = (long) now.getDayOfMonth();
        // 记录签到
        redisTemplate.opsForValue().setBit(key, offset-1, true);
        return Result.ok();
    }

    /**
     * 统计连续点赞次数
     * @return
     */
    @Override
    public Result signCount() {
        // 获取用户id
        Long userId = UserHolder.getUser().getId();
        // key
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = USER_SIGN_KEY + userId.toString() + keySuffix;
        int offset =  now.getDayOfMonth();
        List<Long> list = redisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(offset)).valueAt(0));
        if(list==null || list.isEmpty()){
            return Result.ok(0);
        }
        Long num = list.get(0);
        if(num == null || num ==0){
            return Result.ok(0);
        }
        int count = 0;
        while(true){
            if(num == 1){
                count++;
            }else{
                break;
            }
            num>>>=1;
        }
        return Result.ok(count);
    }

    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName("user_"+RandomUtil.randomString(10));
        return user;
    }
}
